﻿using Furion;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace MESProWebApi.Core
{
    /// <summary>
    /// 数据库上下文对象
    /// </summary>
    public static class DbContext
    {
        #region 字段
        public static List<ConnectionConfig> DbConfigs { get; set; } = App.GetConfig<List<ConnectionConfig>>("ConnectionConfigs");
        /// <summary>
        /// SqlSugar 数据库实例
        /// </summary>
        public static readonly SqlSugarScope Instance = new(
            // 读取 appsettings.json 中的 ConnectionConfigs 配置节点
            DbConfigs
            , db =>
            {
                // 这里配置全局事件，比如拦截执行 SQL
                foreach (var config in DbConfigs)
                {
                    var sqlsugarScope = db.GetConnectionScope(config.ConfigId);//获取当前库
                    MoreSetting(sqlsugarScope);//更多设置

                }


            });

        #endregion 字段

        #region 属性

      

        #endregion 属性

        #region Private 方法

        private static void MoreSetting(SqlSugarScopeProvider db)
        {
            db.CurrentConnectionConfig.MoreSettings = new ConnMoreSettings
            {
                SqlServerCodeFirstNvarchar = true,//设置默认nvarchar
                //TableEnumIsString = true,
            };
            db.CurrentConnectionConfig.ConfigureExternalServices = new ConfigureExternalServices()
            {
                //EntityService = (x, p) => //处理列名
                //{
                //    
                //p.DbColumnName = UtilMethods.ToUnderLine(p.DbColumnName);//ToUnderLine驼峰转下划线方法
                //},
                EntityNameService = (x, p) => //处理表名,系统基础表都以Sys开头
                {
                    p.DbTableName = "Sys_" + p.DbTableName;
                },

                EntityService = (c, p) =>
                {
                    // 值类型可空支持
                    if (p.IsPrimarykey == false && c.PropertyType.IsGenericType &&
                    c.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                    {
                        p.IsNullable = true;
                    }
                }
            };
            //(A)全局生效配置点
            //调试SQL事件，可以删掉
            db.Aop.OnLogExecuting = (sql, pars) =>
            {
                Debug.WriteLine(sql);//输出sql,查看执行sql
                                     //5.0.8.2 获取无参数化 SQL
                                     //UtilMethods.GetSqlString(DbType.SqlServer,sql,pars)
            };
        }

        #endregion Private 方法
    }
}